/**
 * 微前端专用入口文件 (ES模块格式)
 * 被UMD入口文件动态导入
 */
import 'tdesign-vue-next/es/style/index.css';

import TDesign from 'tdesign-vue-next';
import { createApp } from 'vue';

import DashboardApp from './DashboardApp.vue';
import i18n from './locales';
import router from './router';
import pinia from './store';

let app = null;

// 微前端应用管理器
export const createMicroApp = {
  async mount(props) {
    console.log('[MicroEntry] 开始挂载Vue应用, props:', props);

    // 创建Vue应用实例
    app = createApp(DashboardApp);

    // 配置插件
    app.use(pinia);
    app.use(router);
    app.use(TDesign);
    app.use(i18n);

    // 注入全局属性
    if (props.getGlobalState) {
      app.config.globalProperties.$getGlobalState = props.getGlobalState;
    }

    if (props.setGlobalState) {
      app.config.globalProperties.$setGlobalState = props.setGlobalState;
    }

    if (props.messageService) {
      app.config.globalProperties.$messageService = props.messageService;
    }

    // 确定挂载容器
    let container = null;

    if (props && props.container) {
      if (typeof props.container === 'string') {
        container = document.querySelector(props.container);
        console.log(`[MicroEntry] 找到容器: ${props.container}`, container);
      } else {
        container = props.container;
        console.log('[MicroEntry] 使用提供的DOM容器', container);
      }
    }

    if (!container) {
      const selectors = ['#micro-container', '#dashboard-app-app'];
      for (const selector of selectors) {
        container = document.querySelector(selector);
        if (container) {
          console.log(`[MicroEntry] 使用备选容器: ${selector}`);
          break;
        }
      }
    }

    if (!container) {
      container = document.body;
      console.log('[MicroEntry] 使用body作为容器');
    }

    // 清空并挂载
    if (container) {
      container.innerHTML = '';
      app.mount(container);
      console.log('[MicroEntry] ✅ Vue应用挂载成功!');

      // 验证挂载
      setTimeout(() => {
        console.log('[MicroEntry] 挂载验证:');
        console.log('  - 容器内容长度:', container.innerHTML.length);
        console.log('  - 子元素数量:', container.children.length);
        console.log('  - 当前路由:', router.currentRoute.value.path);
      }, 100);
    } else {
      throw new Error('无法找到有效的挂载容器');
    }
  },

  async unmount() {
    console.log('[MicroEntry] 开始卸载Vue应用');

    if (app) {
      app.unmount();
      app = null;
      console.log('[MicroEntry] ✅ Vue应用卸载成功');
    }
  },
};

// 导出创建函数供UMD入口使用
export { createMicroApp as createApp };
